package com.me.forum.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.me.forum.domain.BaseEntity;
import com.me.forum.service.IBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.regex.Pattern;

public abstract class BaseService<TDao extends BaseMapper<T>,T extends BaseEntity> implements IBaseService<T> {
	@Autowired
	protected TDao dao;
	
	@Transactional(rollbackFor = Exception.class)
	@Deprecated
	protected boolean save(T t) {
		return dao.insert(t) == 1;
	}
	
	@Override
	public List<T> getAll() {
		return dao.selectList(new QueryWrapper<>());
	}
	
	@Deprecated
	protected IPage<T> getAll(IPage<T> pageable, Wrapper wrapper) {
		return dao.selectPage(pageable,wrapper);
	}
	
	private T findById(Long id) {
		return dao.selectById(id);
	}
	
	@Transactional(rollbackFor = Exception.class)
	@Deprecated
	protected int update(T t) {
		T user = dao.selectById(t.getId());
		if (user != null) {
			return -1;
		}
		
		return dao.insert(t);
	}
	
	@Transactional(rollbackFor = Exception.class)
	protected Boolean delete(Long id) {
		try {
			dao.deleteById(id);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	@Deprecated
	protected IPage<T> getAll(T entity,String page,String size){
		if ((page != null && !page.isEmpty()) &&
			(size != null && !size.isEmpty()) &&
			Pattern.matches("^\\d{0,10}$",page) &&
			Pattern.matches("^\\d{0,10}$",size)
		) {
			return dao.selectPage(new Page<T>(Long.valueOf(page), Long.valueOf(size)), new QueryWrapper<T>(entity));
		}
		return null;
	}
	
	@Override
	public T findById(String id){
		if (id != null && !id.isEmpty() && Pattern.matches("^\\d{0,19}$",id)) {
			return findById(Long.valueOf(id));
		}
		return null;
	}
	
	@Override
	public Boolean delete(String id) {
		if (id != null && !id.isEmpty() && Pattern.matches("^\\d{0,19}$",id)) {
			return delete(Long.valueOf(id));
		}
		return false;
	}
}
